﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Titan;
using yao.Entity;
using MySql.Data.MySqlClient;
using yao.Mvc;

namespace yao.website.Controllers
{
    /// <summary>
    /// 客户资金流水
    /// </summary>
    public class PurchaseOrderCapitalController : BaseController
    {
        public ActionResult Index(int? p)
        {
            int pageIndex = p == null ? 1 : (int)p;
            ViewBag.PageIndex = pageIndex;

            Providers providers = new Providers();
            using (IDbSession cn = OpenSession())
            {
                //查询客户的所属订单列表
                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(Provider);
                q.Selects.Add(Provider_.ProviderId);//
                q.Selects.Add(Provider_.CompanyNo);//客户编号
                q.Selects.Add(Provider_.CompanyName);//公司简称
                q.Selects.Add(Provider_.ContactName);//联系人
                q.Selects.Add(Provider_.Address);//地址
                q.Selects.Add(Provider_.AccountPayables);//应付款
                q.Selects.Add(Provider_.Employee.EmployeeName);//业务负责人
                q.Selects.Add(Provider_.FinanceRemark);//财务备注
                q.Wheres.Add(Provider_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                q.Wheres.Add(Provider_.AccountPayables.TGreaterThan(0));
                q.ReturnMatchedCount = true;
                q.PageSize = 20;
                q.PageIndex = pageIndex;
                providers.TotalCount = cn.SelectCollection(providers.Items, q);
            }
            return View(providers);
        }


        #region 收款

        private PurchaseOrders GetPurchaseOrders(IDbSession cn,long providerid)
        {
            QueryExpression q = new QueryExpression();
            q.EntityType = typeof(PurchaseOrder);
            q.Selects.Add(PurchaseOrder_.PurchaseOrderId);//销售单号
            q.Selects.Add(PurchaseOrder_.PurchaseOrderNo);//销售单号
            q.Selects.Add(PurchaseOrder_.CreateTime);//订单日期
            q.Selects.Add(PurchaseOrder_.ActualAmount);//订单金额
            q.Selects.Add(PurchaseOrder_.SettleedAmount);//已收款
            q.Selects.Add(PurchaseOrder_.UnSettleedAmount);//应收款
            q.Selects.Add(PurchaseOrder_.IsCompleted);//应收款
            q.Selects.Add(PurchaseOrder_.SettleStatusId);//应收款
            q.Wheres.Add(PurchaseOrder_.ProviderId.TEqual(providerid));
            PurchaseOrders purchaseOrders = new PurchaseOrders();
            cn.SelectCollection(purchaseOrders.Items, q);

            for (int i = 0; i < purchaseOrders.Items.Count; i++)
            {
                QueryExpression query = new QueryExpression();
                query.EntityType = typeof(PurchaseOrderCapital);
                query.Selects.Add(PurchaseOrderCapital_.PurchaseOrderCapitalId);
                query.Selects.Add(PurchaseOrderCapital_.PurchaseOrderId);
                query.Selects.Add(PurchaseOrderCapital_.CapitalTime);//收款时间
                query.Selects.Add(PurchaseOrderCapital_.Amount);//金额
                query.Selects.Add(PurchaseOrderCapital_.PaymentType.PaymentTypeName);//收款方式
                query.Selects.Add(PurchaseOrderCapital_.Remark);//备注
                query.Wheres.Add(PurchaseOrderCapital_.PurchaseOrderId.TEqual(purchaseOrders.Items[i].PurchaseOrderId));
                PurchaseOrderCapitals PurchaseOrderCapitals = new PurchaseOrderCapitals();
                cn.SelectCollection(PurchaseOrderCapitals.Items, query);
                purchaseOrders.Items[i].PurchaseOrderCapitals = PurchaseOrderCapitals;
            }
            return purchaseOrders;
        }

        public ActionResult Receivables(long providerid)
        {
            Provider Provider = new Provider() { ProviderId = providerid };

            using (IDbSession cn = OpenSession())
            {
                //查询供应商
                cn.Select(Provider, Provider_.CompanyName, Provider_.CompanyNo);
                ViewBag.Title = "付款-" + Provider.CompanyNo;
                ViewBag.CompanyName = Provider.CompanyName;//公司简称
                ViewBag.ProviderId = Provider.ProviderId;//客户Id
                return View(GetPurchaseOrders(cn,providerid));
            }
        }


        [HttpPost]
        public ActionResult Receivables(PurchaseOrderCapital model)
        {
            long providerid;
            long.TryParse(Request.Form["ProviderId"], out providerid);
            Provider provider = new Provider() { ProviderId = providerid };
            using (IDbSession cn = OpenSession())
            {
                try
                {
                    cn.BeginTransaction();

                    //查询客户
                    cn.Select(provider, Provider_.CompanyName, Provider_.CompanyNo);
                    ViewBag.Title = "付款-" + provider.CompanyNo;
                    ViewBag.ProviderName = provider.CompanyName;//客户名称
                    ViewBag.ProviderId = provider.ProviderId;//客户Id



                    long PurchaseOrderCapitalCount;
                    if (long.TryParse(Request.Form["PurchaseOrderCapitalCount"], out PurchaseOrderCapitalCount))
                    {
                        #region 获取表单数据
                        PurchaseOrderCapitals purchaseOrderCapitals = new PurchaseOrderCapitals();
                        for (int i = 0; i < PurchaseOrderCapitalCount; i++)
                        {
                            DateTime capitalTime;
                            DateTime.TryParse(Request.Form["CapitalTime_" + i], out capitalTime);

                            decimal amount;
                            decimal.TryParse(Request.Form["Amount_" + i], out amount);

                            long paymentTypeId;
                            long.TryParse(Request.Form["PaymentTypeId_" + i], out paymentTypeId);

                            string remark = Request.Form["Remark_" + i];

                            long purchaseOrderId;
                            long.TryParse(Request.Form["PurchaseOrderId_" + i], out purchaseOrderId);

                            if (amount <= 0 || paymentTypeId <= 0 || capitalTime == null || purchaseOrderId <= 0)
                            {
                                continue;
                            }

                            PurchaseOrderCapital purchaseOrderCapital = new PurchaseOrderCapital
                            {
                                Amount = amount,
                                CapitalEmployeeId = CurrentEmployee.EmployeeId,
                                CapitalTime = capitalTime,
                                PaymentTypeId = paymentTypeId,
                                PurchaseOrderId = purchaseOrderId,
                                Remark = remark
                            };
                            purchaseOrderCapitals.Items.Add(purchaseOrderCapital);
                        }
                        #endregion

                        if (purchaseOrderCapitals.Items.Count < 0)
                        {
                            AddPageError("提交数据有误");
                            return View(GetPurchaseOrders(cn, providerid));
                        }

                        foreach (PurchaseOrderCapital purchaseOrderCapital in purchaseOrderCapitals.Items)
                        {
                            cn.Insert(purchaseOrderCapital);

                            #region 订单资金和结算状态
                            MySqlCommand cmd = new MySqlCommand("update PurchaseOrder set UnSettleedAmount=UnSettleedAmount+@UnSettleedAmount,SettleedAmount=SettleedAmount+@SettleedAmount,SettleStatusId=@SettleStatusId where PurchaseOrderId=@PurchaseOrderId");
                            cmd.Parameters.AddWithValue("@UnSettleedAmount", -purchaseOrderCapital.Amount);
                            cmd.Parameters.AddWithValue("@SettleedAmount", purchaseOrderCapital.Amount);
                            cmd.Parameters.AddWithValue("@SettleStatusId", SettleStatus.SettleedPart);
                            cmd.Parameters.AddWithValue("@PurchaseOrderId", purchaseOrderCapital.PurchaseOrderId);
                            cn.ExecuteNonQuery(cmd);

                            PurchaseOrder purchaseOrder = new PurchaseOrder { PurchaseOrderId = purchaseOrderCapital.PurchaseOrderId };
                            cn.Select(purchaseOrder, PurchaseOrder_.IsCompleted, PurchaseOrder_.SettleStatusId, PurchaseOrder_.UnSettleedAmount);
                            if (purchaseOrder.UnSettleedAmount == 0)
                            {
                                purchaseOrder.IsCompleted = true;
                                purchaseOrder.SettleStatusId = SettleStatus.SettleedComplete;
                                cn.Update(purchaseOrder, PurchaseOrder_.IsCompleted, PurchaseOrder_.SettleStatusId);
                            }

                            #region 修改客户表
                            if (purchaseOrder.IsCompleted && purchaseOrder.SettleStatusId == SettleStatus.SettleedComplete)
                            {
                                MySqlCommand cmdProvider = new MySqlCommand("update Provider set AccountPayables=AccountPayables+@AccountPayables,NotCompletedOrderCount=NotCompletedOrderCount+@NotCompletedOrderCount where ProviderId=@ProviderId");
                                cmdProvider.Parameters.AddWithValue("@AccountPayables", -purchaseOrderCapital.Amount);
                                cmdProvider.Parameters.AddWithValue("@NotCompletedOrderCount", -1);
                                cmdProvider.Parameters.AddWithValue("@ProviderId", provider.ProviderId);
                                cn.ExecuteNonQuery(cmdProvider);
                            }
                            else
                            {
                                MySqlCommand cmdProvider = new MySqlCommand("update Provider set AccountPayables=AccountPayables+@AccountPayables where ProviderId=@ProviderId");
                                cmdProvider.Parameters.AddWithValue("@AccountPayables", -purchaseOrderCapital.Amount);
                                cmdProvider.Parameters.AddWithValue("@ProviderId", provider.ProviderId);
                                cn.ExecuteNonQuery(cmdProvider);
                            }
                            #endregion

                            #endregion
                        }
                    }
                    cn.Commit();
                }
                catch (Exception ex)
                {
                    cn.Rollback();
                    throw new BusinessException(ex.Message);
                }
            }
            return new IframeResult(Url.Action("Receivables", new { providerId = provider.ProviderId }), Url.Action("Index"));

        }
        #endregion


    }
}
